<?php

namespace App\Admin\Forms;

use App\Http\Logic\OrderLogic;
use App\Models\SwtOrderRefund;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class RejectRefundOrderForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $id = $this->payload['id'] ?? null;

        if($input['status'] == 1) {
            $refund_order_info = SwtOrderRefund::with('order') -> where('id',$id)->firstOrFail();

            $order_info = $refund_order_info -> toArray();

            $out_order_no = $order_info['order']['order_sn'];

            $amount = ($order_info['order']['pay_amount'] - $order_info['order']['refund_amount']) / 100;


            if($amount < $refund_order_info['refund_amount'] / 100) {
                return $this->response()->error('退款金额不足');
            }

            $res = OrderLogic::refundOrder($out_order_no, $refund_order_info['refund_amount'], '审批退款');

            if (!$res) {
                return $this->response()->error('退款失败');
            }
        }

        $res = SwtOrderRefund::where('id',$id)->update(['status' => $input['status'], 'reject_notes' => $input['notes'] ?? '']);

        if (!$res) {
            return $this->response()->error('操作失败');
        }

        return $this->response()->success('操作成功')->refresh();
    }

    public function form()
    {
        $this->radio('status', '状态')->options([1 => '同意', 2 => '驳回']) -> rules('required') -> required();

        $this->textarea('notes', '原因');
    }

    public function default()
    {
        return [
            'status' => 1,
        ];
    }
}
